package system.security;

import framework.config.UserConfig;
import framework.security.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import security.vo.UserDetail;

/**
 * 授权服务的默认实现
 */
@Configurable
public class AuthServiceImpl implements framework.security.AuthService {
    @Autowired
    private UserConfig userConfig;

    @Override
    public boolean isSupperAdmin() {
        Long superAdminId = this.userConfig.getSuperAdminId();
        if (superAdminId == null) return false;
        //
        Long accountId = this.getAccountId();
        if (accountId == null) return false;
        //
        return superAdminId.equals(accountId);
    }

    @Override
    public Long getAccountId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication.getPrincipal() instanceof UserDetail)) {
            return null;
        }
        UserDetail detail = (UserDetail) authentication.getPrincipal();
        if (detail != null && detail.getAccount() != null)
            return detail.getAccount().getId();
        return null;
    }

    @Override
    public Account getAccount() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication.getPrincipal() instanceof UserDetail)) {
            return null;
        }
        UserDetail detail = (UserDetail) authentication.getPrincipal();
        if (detail != null && detail.getAccount() != null)
            return detail.getAccount();
        return null;
    }

    @Override
    public boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication.getPrincipal() instanceof UserDetail)) {
            return false;
        }
        return authentication.isAuthenticated();
    }

    @Override
    public String getSecret() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String credentials = (String) authentication.getCredentials();
        return credentials;
    }

    @Override
    public boolean hasPermission(String permission) {
        if (permission == null)
            return false;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        for (GrantedAuthority authority : authentication.getAuthorities()) {
            if (permission.equals(authority.getAuthority()))
                return true;
        }
        return false;
    }
}
